<?php
namespace app\index\model;
use think\Db;
/**
 * Created by Submint Text.
 * User: hetaoren<452649510@qq.com>
 * Date: 2017/03/10
 * Explain: 订单类
 */
class Orders extends Base{
     /**
      *  订单列表
      */
	public function pageQuery(){
		$areaIdPath = input('areaIdPath');
		$where = [];
		$where['dataFlag'] = 1;
		if($areaIdPath !='')$where['areaIdPath'] = ['like',$areaIdPath."%"];
		$diseaseId = input('diseaseId');
		if($diseaseId != '')$where['diseaseId'] = $diseaseId;
		$staffId = input('staffId');
		if($staffId != '')$where['staffId'] = $staffId;
		$goodsName = input('goodsName');
		if($goodsName != '')$where['goodsName'] = ['like',"%$goodsName%"];
		$user_name = input('user_name');
		if($user_name != '')$where['user_name'] = ['like',"%$user_name%"];
		$startDate = input('startDate');
		$endDate = input('endDate');
		if($startDate!='')$where['createTime'] = ['>=',$startDate];
		if($endDate!='')$where[' createTime'] = ['<=',$endDate];		
		$total0 = input('total0');
		$total1 = input('total1');
		if($total0!='')$where['total'] = ['>=',$total0];
		if($total1!='')$where[' total'] = ['<=',$total1];	
		if(session("HTR_STAFF.staffRoleId") == 2)$where['shopId'] = session("HTR_STAFF.shopId");
		if(session("HTR_STAFF.staffRoleId") == 3)$where['staffId'] = session("HTR_STAFF.staffId");
		$page = $this->where($where)->order('orderId desc')->paginate(input('pagesize/d'))->toArray();
		if(count($page['Rows'])>0){
        	$diseaseList = model('disease')->where(['dataFlag'=>1])->column('diseaseId,diseaseName');
        	$staffList = model('staffs')->where(['dataFlag'=>1])->column('staffId,staffName');
			foreach ($page['Rows'] as $key => $v){
				$page['Rows'][$key]['diseaseName'] = isset($diseaseList[$v['diseaseId']]) ? $diseaseList[$v['diseaseId']] : '';
				$page['Rows'][$key]['staffName'] = isset($staffList[$v['staffId']]) ? $staffList[$v['staffId']] : '';
  				$page['Rows'][$key]['areaPathName'] = $this->areaPathName($v['areaIdPath']);
			}
		}
		return $page;
	}

	public function areaPathName($areaIdPath){
		$areaIdPath = explode('_',$areaIdPath);
		$areaPathName = '';
		foreach($areaIdPath as $v){
			if($v)$areaPathName .= ' '.model('Areas')->getNames($v);
		}
		return $areaPathName;
	}
	/**
	 * 修改库存
	 */
	public function changeStock($goodsId,$shopId,$saleNum,$type=0){
		try{
        	$stock = model('stocks')->where(['goodsId'=>$goodsId,'shopId'=>$shopId])->find();
        	if(!$stock)throw \Exception('店铺没有该商品');
        	if($type == 0){
				if($stock->goodsStock < $saleNum)throw \Exception('店铺库存不足');
	        	$stock->goodsStock -= $saleNum;
	        	$stock->saleNum += $saleNum;
        	}else{        		
	        	$stock->goodsStock += $saleNum;
	        	$stock->saleNum -= $saleNum;
        	}
        	$result = $stock->save();
        	if(false === $result)throw \Exception('库存修改失败');
        	$goods = model('goods')->where(['goodsId'=>$goodsId])->find();
        	if(!$goods)throw \Exception('没有该商品');
        	if($type == 0){
				if($goods->goodsStock < $saleNum)throw \Exception('库存不足');
	        	$goods->goodsStock -= $saleNum;
	        	$goods->saleNum += $saleNum;
        	}else{
	        	$goods->goodsStock += $saleNum;
	        	$goods->saleNum -= $saleNum;      		
        	}
        	$result = $goods->save();
        	if(false === $result)throw \Exception('库存修改失败');  
		}catch (\Exception $e) {
            return $e->getMessage();  
            // return false; 
        }
        return true; 
	}
	/**
	 * 新增
	 */
	public function add(){
		$data = input('post.');
		$data["total"] = $data["salePrice"] * $data["saleNum"];
		if($data['createTime'] == '')$data['createTime'] = date('Y-m-d');
		HTRUnset($data, 'orderId');
		Db::startTrans();
		try{
			$result = $this->allowField(true)->save($data);
	        if(false === $result)throw \Exception('新增失败');  
		    $result = $this->changeStock($data["goodsId"],$data["shopId"],$data["saleNum"]);
		    if(true !== $result)throw \Exception($result);  

			model('Remind')->where(['is_read'=>0,'type'=>1,'user_id'=>$data['user_id']])->delete();	 
			if($data['remind']){				
				$remind = explode(',',$data['remind']);
	    		$_data = [];
				foreach($remind as $v){
					$remindTime = strtotime($data['createTime']) + $v * 86400;
	    			$_data[] = ['user_id'=>$data['user_id'],'type'=>1,'day'=>$v,'remindTime'=>date('Y-m-d',$remindTime)];
				}
				model('Remind')->insertAll($_data);	   					
			} 			


        	$diseaseId = model('orders')->group('diseaseId')->where('user_id',$data['user_id'])->order('diseaseId asc')->column('diseaseId');
        	model('users')->where('user_id',$data['user_id'])->update(['diseaseId'=>join(',',$diseaseId)]);
        	model('users')->where('user_id',$data['user_id'])->setInc('total',$data["total"]);

        	Db::commit();
        	return HTRReturn("新增成功", 1);
		}catch (\Exception $e) {
            Db::rollback();
            return HTRReturn($e->getMessage());
        }
	}
    /**
	 * 编辑
	 */
	public function edit(){
		$orderId = input('post.orderId/d',0);
		$data = input('post.');
		$data["total"] = $data["salePrice"] * $data["saleNum"];
		if($data['createTime'] == '')$data['createTime'] = date('Y-m-d');
		$order = $this->get($data["orderId"]);
		HTRUnset($data, 'orderId');
		Db::startTrans();
		try{
			$result = $this->allowField(true)->save($data,['orderId'=>$orderId]);
	        if(false === $result)throw \Exception('编辑失败');          	
		    $result = $this->changeStock($order->goodsId,$order->shopId,$order->saleNum,1);
		    if(true !== $result)throw \Exception($result);
		    model('users')->where('user_id',$data['user_id'])->setDec('total',$order->total);
		    $result = $this->changeStock($data["goodsId"],$data["shopId"],$data["saleNum"]);
		    if(true !== $result)throw \Exception($result);		    
        	model('users')->where('user_id',$data['user_id'])->setInc('total',$data["total"]);  
    		if($order->user_id != $data['user_id']){
				model('Remind')->where(['is_read'=>0,'type'=>1,'user_id'=>$order->user_id])->delete();	
    		}
    		if($order->createTime != $data['createTime'] || $order->remind != $data['remind']){
				model('Remind')->where(['is_read'=>0,'type'=>1,'user_id'=>$data['user_id']])->delete();	
				if($data['remind']){				
					$remind = explode(',',$data['remind']);
		    		$_data = [];
					foreach($remind as $v){
						$remindTime = strtotime($data['createTime']) + $v * 86400;
						if($remindTime < time())continue;
		    			$_data[] = ['user_id'=>$data['user_id'],'type'=>1,'day'=>$v,'remindTime'=>date('Y-m-d',$remindTime)];
					}
					model('Remind')->insertAll($_data);	   					
				}
    		}

        	$diseaseId = model('orders')->group('diseaseId')->where('user_id',$data['user_id'])->order('diseaseId asc')->column('diseaseId');
        	model('users')->where('user_id',$data['user_id'])->update(['diseaseId'=>join(',',$diseaseId)]);

	    	Db::commit();
	    	return HTRReturn("编辑成功", 1);
		}catch (\Exception $e) {
            Db::rollback();
            return HTRReturn($e->getMessage());
        }
	}

	/**
	 * 删除订单
	 */
	public function del(){
		$id = input('post.id/d');
		$order = $this->get($id);
		$order->dataFlag = -1;
		Db::startTrans();
		try{
		    $result = $order->save();		    
	        if(false === $result)throw \Exception('删除失败');          	
		    $result = $this->changeStock($order->goodsId,$order->shopId,$order->saleNum,1);
		    if(true !== $result)throw \Exception($result);  
		    model('users')->where('user_id',$data['user_id'])->setDec('total',$order->total);
        	$diseaseId = model('orders')->group('diseaseId')->where('user_id',$order->user_id)->order('diseaseId asc')->column('diseaseId');
        	model('users')->where('user_id',$order->user_id)->update(['diseaseId'=>join(',',$diseaseId)]);
        	Db::commit();
        	return HTRReturn("删除成功", 1);
		}catch (\Exception $e) {
            Db::rollback();
            return HTRReturn($e->getMessage());
        }
	}
}
